package com.ming.system;

import com.ming.common.beetl.util.BeetlSqlUtil;
import com.ming.common.generate.template.enable.EnableGenerate;
import com.ming.common.ivy.IvyDict;
import org.beetl.sql.core.SQLManager;
import org.python.util.PythonInterpreter;
import org.redisson.spring.starter.RedissonAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;

import java.util.Properties;

@EnableGenerate(basePackages = {"com.ming"})
@ComponentScans(@ComponentScan(basePackages = {"com"}))
@SpringBootApplication(exclude = {RedissonAutoConfiguration.class})
public class IvyApplication {

    public static void main(String[] args) {
        SpringApplication.run(IvyApplication.class, args);
        // Jython环境初始化
        jython();

        // 创建一个关闭钩子
        Thread shutdownHook = new Thread(() -> {
            // 在 JVM 即将关闭时执行的操作
            // destroyClass(SpringBeanUtil.getBean("sqlManager"));
        });
        // 将关闭钩子添加到 JVM
        Runtime.getRuntime().addShutdownHook(shutdownHook);
        // 模拟 JVM 关闭
        // simulateJvmShutdown();


    }

    private static void jython(){
        SQLManager defaultSQLManager = BeetlSqlUtil.NEW().getDefaultSQLManager();
        IvyDict ivyDict = defaultSQLManager.lambdaQuery(IvyDict.class).andEq(IvyDict::getCode,"ivy_jython_path").single();
        if(ivyDict != null){
            Properties props = new Properties();
            Properties preprops = System.getProperties();
            props.put("python.home", ivyDict.getValue());//jython安装目录
            PythonInterpreter.initialize (preprops, props, new String[]{});
        }
    }

    private static void simulateJvmShutdown() {
        // 模拟 JVM 关闭前的清理工作
        // 例如：关闭数据库连接、保存状态等

        // JVM 关闭
        System.exit(0);
    }

}
